import axios from 'axios'
import router from "@/router";

axios.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        return Promise.resolve(error.response);
    }
);
axios.defaults.withCredentials = true;
function checkStatus(response) {
    console.log("resoonse",response)
    if (
        response &&
        (response.status === 200 ||
            response.status === 304 ||
            response.status === 400||
            response.status === 401)
    ) {
      var data={
        status:response.status,
        data:response.data,
        msg:response.status === 200?"正常":response.data.detail
      }
        return data;
        // 如果不需要除了data之外的数据，可以直接 return response.data
    }
    // 异常状态下，把错误信息返回去
    return {
        status: -404,
        msg: "网络异常",
    };
}

function checkCode(res) {
    // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
    if (res.status === -404) {
        // message.error('网络错误');
        return;
    }

    if (res.status === 403) {
        // message.error('请重新登录');
        router.push('/login')
        return;
    }
  console.log("checkcode",res);
    return res;
}

export default {
    upload(url, data) {
        console.log("data:",data)
        return axios({
            method: "POST",
            url,
            data,
            timeout: 50000,
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                'Content-Type': 'multipart/form-data',
                "Authorization": "Bearer "+localStorage.getItem("access_token") || null
            },
            withCredentials: true
        }).then((response) => {
            return checkStatus(response);
        })
            .then((res) => {
                return checkCode(res);
            });
    },

    post2(url, data, flag = 0) {
      // console.log('sessionStorage===', localStorage.getItem('token'))
      if (flag === 0 && !localStorage.getItem("access_token")) {
          router.push('/login')
          return
      }
      return axios(
          {
              method: "POST",
              url,
              data,
              timeout: 50000,
              headers: {
                  "X-Requested-With": "XMLHttpRequest",
                  "Authorization": "Bearer "+localStorage.getItem("access_token") || null
              },
              withCredentials: true,
          }
      )
          .then((response) => {
              return checkStatus(response);
          })
          // .then((res) => {
          //     return checkCode(res);
          // });
  },

    post(url, data, flag = 0) {
        // console.log('sessionStorage===', localStorage.getItem('token'))
        if (flag === 0 && !localStorage.getItem("access_token")) {
            router.push('/login')
            return
        }
        return axios(
            {
                method: "POST",
                url,
                data,
                timeout: 50000,
                headers: {
                    "X-Requested-With": "XMLHttpRequest",
                    "Content-Type": "application/json; charset=UTF-8",
                    "Authorization": "Bearer "+localStorage.getItem("access_token") || null
                },
                withCredentials: true,
            }
        )
            .then((response) => {
                return checkStatus(response);
            })
            .then((res) => {
                return checkCode(res);
            });
    },
    get(url, params, flag = 0) {
        // console.log('sessionStorage===', sessionStorage.getItem('token'))
        if (flag === 0 && !localStorage.getItem("access_token")) {
          router.push('/login')
          return
        }
        console.log(url,params);
        return axios(
            {
                method: "get",
                url,
                params, // get 请求时带的参数
                timeout: 50000,
                headers: {
                    "X-Requested-With": "XMLHttpRequest",
                    'Content-Type': 'application/x-www-form-urlencoded',
                    "Authorization": "Bearer "+localStorage.getItem("access_token") || null,
                    'Accept': 'application/json'
                },
                withCredentials: true,
            },
        )
            .then((response) => {
                return checkStatus(response);
            })
            .then((res) => {
                return checkCode(res);
            });
    },
    // download(url, params, flag = 0) {
    //     console.log('sessionStorage===', sessionStorage.getItem('token'))
    //     // if (flag === 0 && !sessionStorage.getItem('token')) {
    //     //     router.push('/login');
    //     //     return;
    //     // }
    //     return axios(
    //         {
    //             method: "post",
    //             url,
    //             params, // get 请求时带的参数
    //             timeout: 10000,
    //             headers: {
    //                 "X-Requested-With": "XMLHttpRequest",
    //                 'jwt_token': sessionStorage.getItem('token') || null,
    //                 'Content-Type': 'application/octet-stream;charset=utf-8'
    //             },
    //             withCredentials: true,
    //         },
    //     )
    //         .then((response) => {
    //             return checkStatus(response);
    //         })
    //         .then((res) => {
    //             return checkCode(res);
    //         });
    // }
};




// 1. 导入axios和Vue
// import axios from 'axios';
// import { reactive } from 'vue';

// // 2. 创建一个axios实例
// const http = axios.create({
//   baseURL: '', // 根据你的实际情况修改
// });

// // 3. 创建请求拦截器
// http.interceptors.request.use((config) => {
//   // 可以在这里做一些请求前的处理，如添加token等
//   return config;
// }, (error) => {
//   return Promise.reject(error);
// });

// // 4. 创建响应拦截器
// http.interceptors.response.use((response) => {
//   // 可以在这里做一些响应后的处理，如错误处理、数据统一处理等
//   return response.data;
// }, (error) => {
//   return Promise.reject(error);
// });

// // 5. 封装GET请求方法
// function get(url,params) {

//   if(localStorage.getItem("access_token")==null) {
//     localStorage.setItem("access_token","");
//     }
//   return http.get(url, { 
//     params:params,
//     headers: {
//       Authorization: "Bearer "+localStorage.getItem("access_token")
//     }
//   });
// }


// function getWithParam(url, params) {
//   if (localStorage.getItem("access_token") == null) {
//     localStorage.setItem("access_token", "");
//   }
  
//   let endpoint = url;
  
//   // Check if params exist
//   const queryString = new URLSearchParams(params).toString();
//   const requestUrl = `${endpoint}?${queryString}`;
//   console.log("http://localhost:9876"+requestUrl);
  
//   return http.get(requestUrl,{}, {
//      headers: {
//      'Accept': 'application/json', // 指示服务器返回JSON格式数据
//      Authorization: "Bearer " + localStorage.getItem("access_token")
//      }
//     }); 
// }


// function put(url, params) {
//   if (localStorage.getItem("access_token") == null) {
//     localStorage.setItem("access_token", "");
//   }
  
//   let endpoint = url;
  
//   // Check if params exist
//   const queryString = new URLSearchParams(params).toString();
//   const requestUrl = `${endpoint}?${queryString}`;
//   console.log("http://localhost:9876"+requestUrl);
  
//   return http.put(requestUrl, {
//      headers: {
//      'Accept': 'application/json', // 指示服务器返回JSON格式数据
//      Authorization: "Bearer " + localStorage.getItem("access_token")
//      }
//     }); 
// }


// function deleteMethod(url, params) {
//   if (localStorage.getItem("access_token") == null) {
//     localStorage.setItem("access_token", "");
//   }
  
//   let endpoint = url;
  
//   // Check if params exist
//   const queryString = new URLSearchParams(params).toString();
//   const requestUrl = `${endpoint}?${queryString}`;
//   console.log("http://localhost:9876"+requestUrl);
  
//   return http.delete(requestUrl, {
//      headers: {
//      'Accept': 'application/json', // 指示服务器返回JSON格式数据
//      Authorization: "Bearer " + localStorage.getItem("access_token")
//      }
//     }); 
// }

// // 6. 封装POST请求方法
// function post(url, data) {
 
//   if(localStorage.getItem("access_token")==null) {
//     localStorage.setItem("access_token","");
//     }

//   return http.post(url, data,{
//     headers: {
//       Authorization: "Bearer "+localStorage.getItem("access_token")
//     }
//   });
// }

// // // 6. 封装POST请求方法
// // function post2(url, data) {
// //   return http.post(url, data,{
// //     headers: {
// //     'Content-Type': 'multipart/form-data',
// //       Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsImV4cCI6MTY5Mjg1MTI5OX0.e-6w7AD2vfE4IXLJweS-k8FMtlEvurB_VpqJL0qbJDg"
// //     }
// //   });
// // }
// //上传文件
// function upload(url, data) {
//   if(localStorage.getItem("access_token")==null) {
//     localStorage.setItem("access_token","0");
//     }
//   return http.post(url, data,{
//     headers: {
//       'Content-Type': 'multipart/form-data',
//        Authorization: "Bearer "+localStorage.getItem("access_token")
//     }
//   });
// }


// // 7. 导出网络请求相关方法
// export default {
//   get,
//   getWithParam,
//   put,
//   deleteMethod,
//   post,
//   upload
// };